/* This javascript module includes functions for dealing with the user interface.
 * 
 * author: Chris Barnett
 * 
 */

if (typeof org === 'undefined'){ 
	org = {};
} else if (typeof org !== "object"){
	throw new Error("org already exists and is not an object");
}

// Repeat the creation and type-checking code for the next level
if (typeof org.OpenGeoPortal === 'undefined'){
	org.OpenGeoPortal = {};
} else if (typeof org.OpenGeoPortal !== "object"){
    throw new Error("org.OpenGeoPortal already exists and is not an object");
}

org.OpenGeoPortal.UserInterface = function(){
	jQuery("#tabs").tabs({selected: 1});
	this.togglePanels();
	jQuery('.searchBox').keypress(function(event){
		if (event.keyCode == '13') {
			org.OpenGeoPortal.ui.searchSubmit();
		}
	});
	jQuery("#geosearch").keypress(function(event){
		if (event.keyCode == '13') {
			org.OpenGeoPortal.ui.geocodeLocation();
		}
	});
	jQuery(document).bind("eventMoveEnd", function(){
		if (org.OpenGeoPortal.Utility.whichTab().name == 'search'){
			org.OpenGeoPortal.ui.filterResults();
		}
	});
	jQuery(document).bind('tabsshow', function(event, ui) {
		var tabObj = org.OpenGeoPortal.Utility.whichTab();
		switch(tabObj.name){
		case 'search':
			org.OpenGeoPortal.ui.filterResults();
			break;
		case 'saved':
			jQuery('#savedLayers').dataTable().fnDraw();
			break;
		}
	});
	
	//buttons
    jQuery("#basemapSelect").button();
    jQuery("#basemapMenu").buttonset();
    jQuery("#basemapDropdown").hover(function(){jQuery("#basemapMenu").show();}, function(){jQuery("#basemapMenu").hide();});
	//set mouse cursor behavior
	this.mouseCursor();
	this.resizePanels();
	var that = this;
	jQuery("#mapLoadIndicator").bind("ajaxSend", function(){
			that.loadIndicator(jQuery(this).attr("id"), "show");
		 }).bind("ajaxComplete", function(){
			that.loadIndicator(jQuery(this).attr("id"), "hide");
		 });
	
	//'hover' for graphics that are not background graphics
	jQuery('.olControlModPanZoomBar img[id*="zoomin"]').bind("mouseenter", function(){
		jQuery(this).attr("src", "javascript/openlayers/OpenLayers-2.10/img/slider_plus_hover.png");
	});
	
	jQuery('.olControlModPanZoomBar img[id*="zoomin"]').bind("mouseleave", function(){
		jQuery(this).attr("src", "javascript/openlayers/OpenLayers-2.10/img/zoom-plus-mini.png");
	});
	
	jQuery('.olControlModPanZoomBar img[id*="zoomout"]').bind("mouseenter", function(){
		jQuery(this).attr("src", "javascript/openlayers/OpenLayers-2.10/img/slider_minus_hover.png");
	});
	
	jQuery('.olControlModPanZoomBar img[id*="zoomout"]').bind("mouseleave", function(){
		jQuery(this).attr("src", "javascript/openlayers/OpenLayers-2.10/img/zoom-minus-mini.png");
	});
	
	jQuery('#tabs a').bind("mousedown", function(){
		//console.log(jQuery(this));
			var tabImage = jQuery(this).find("img");
			if (tabImage.length > 0){
				tabImage.attr("src", "media/shoppingcart_on.png");
			} else {
				jQuery('#tabs a img').attr("src", "media/shoppingcart.png");
			}
	});
};

org.OpenGeoPortal.UserInterface.prototype.showSearchResults = function(){
	jQuery("div#welcomeTextSearchTab").remove();	
	jQuery("#resultsSubHeader > span.sub_headerButtons").css("display", "inline");
	jQuery("#resultsTable").css("display", "block");
	jQuery("#searchResultsNavigation").css("display", "block");
};

org.OpenGeoPortal.UserInterface.prototype.filterState = function(){
	return jQuery('#basicSearchMapFilter').attr("checked");
};
//also call when switching tabs to a search tab, onchange of mapfilter select boxes
org.OpenGeoPortal.UserInterface.prototype.filterResults = function(){
	if (this.filterState()){
		this.searchSubmit();
	}
};


org.OpenGeoPortal.UserInterface.prototype.baseMapChanged = function()
{
    var value = jQuery('input:radio[name=basemapRadio]:checked').val();
    org.OpenGeoPortal.map.setBackgroundMap(value);
};


org.OpenGeoPortal.UserInterface.prototype.geocodeLocation = function()
{
	//var value = escape(jQuery("#geosearch").val());
	var value = jQuery("#geosearch").val();
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': value}, function(results, status) {
		if (status != 'OK'){
			jQuery("#geosearch").val("Place name not found");
			return;
		}
		jQuery("#geosearch").val(results[0].formatted_address);
		var	maxY = results[0].geometry.viewport.getNorthEast().lat();
		var	maxX = results[0].geometry.viewport.getNorthEast().lng();
		var	minY = results[0].geometry.viewport.getSouthWest().lat();
		var	minX = results[0].geometry.viewport.getSouthWest().lng();
	  	var extent = minX + "," + minY + "," + maxX + "," + maxY;
	  	//zooms to actual extent, rather than a latitude delta
		org.OpenGeoPortal.map.zoomToLayerExtent(extent);
        });
};

org.OpenGeoPortal.UserInterface.prototype.clearInput = function(divName){
		jQuery('#' + divName + ' :input').each(function(){
			var type = this.type;
			var tag = this.tagName.toLowerCase();
			if (type == 'text' || type == 'password' || tag == 'textarea'){
				this.value = '';
			} else if (type == 'checkbox' || type == 'radio'){
				this.checked = false;
			} else if (tag == 'select'){
				this.selectedIndex = 0;
			}
		});
};

org.OpenGeoPortal.UserInterface.prototype.clearDefault = function(inputFieldName)
{
    var searchTextElement = document.getElementById(inputFieldName);
    if (searchTextElement == null)
	return;
    var currentValue = searchTextElement.value;
    if (currentValue.indexOf("Search") == 0)
        searchTextElement.value = "";
};

org.OpenGeoPortal.UserInterface.prototype.searchSubmit = function(){
	org.OpenGeoPortal.resultsTableObj.searchRequest(0);
};

org.OpenGeoPortal.UserInterface.prototype.getCheckboxValue = function(id){
	var query = "#" + id + ":checked";
	var value = jQuery(query).val();
	if (value)
		value = "on";
	else
		value = "off";
	return value;
};

//really, this should probably go elsewhere
org.OpenGeoPortal.UserInterface.prototype.adjustTableLength = function(tableID){
	var tableID = 'searchResults';
    if (tableID == 'searchResults'){
    	org.OpenGeoPortal.resultsTableObj.setTableLength();
    } else {
  	  throw new Error("The specified table is not applicable.");
    }
};

org.OpenGeoPortal.UserInterface.prototype.toggleSearch = function(thisObj){
	var thisID = jQuery(thisObj).attr('id');
	if (thisID == 'moreSearchOptions'){
		  jQuery('#basicSearchBox').animate(
    			  {height: 'hide'},
    			  {queue: false, duration: 0}
    		  );
    		  jQuery('#advancedSearchBox').animate(
    			  {height: 'show'},
    			  {queue: false, duration: 0}
    		  );
	} else if (thisID == 'lessSearchOptions'){
		  jQuery('#basicSearchBox').animate(
    			  {height: 'show'},
    			  {queue: false, duration: 0}
    		  );
    		  jQuery('#advancedSearchBox').animate(
    			  {height: 'hide'},
    			  {queue: false, duration: 0}
    		  );	
	}
	org.OpenGeoPortal.resultsTableObj.setTableLength();
};

org.OpenGeoPortal.UserInterface.prototype.togglePanels = function(){
    	jQuery('.arrow_buttons > img').click( function () {
          var rollUp = "media/button_arrow_up.png";
          var rollDown = "media/button_arrow_down.png";
          var rollLeft = "media/button_arrow_left.png";
          var rollRight = "media/button_arrow_right.png";
          var that = this;
          var tabDiv = jQuery(this).parents('.ui-tabs-panel').last();
          var userDiv = tabDiv.find('.searchBox')[0];
          var tableID = tabDiv.find('.display')[0];
          switch (jQuery(this).attr('src')){
          case rollUp: 
        	  jQuery(userDiv).toggle("blind",{},250, function(){org.OpenGeoPortal.resultsTableObj.setTableLength();});
        	  jQuery(this).attr('src', rollDown);
          break;
          case rollDown:
  			  jQuery(userDiv).toggle("blind",{},250, function(){org.OpenGeoPortal.resultsTableObj.setTableLength();});
  			  jQuery(this).attr('src', rollUp);
          break;	
          case rollLeft:
          	//logic to expand map to full size
        	  var panelSelector = jQuery("#left_col");
        	  if (panelSelector.width() <= 450){
        		  panelSelector.animate(
        			  {width: 'hide'},
        			  {queue: false, duration: 0,
        				  complete: function(){
        				  org.OpenGeoPortal.resultsTableObj.sizeCells("searchResults");}  
        			  }
        		  );
        		  jQuery("#roll_right").show().animate(
        			  {width: '18px'},
        			  {queue: false, duration: 0}
        		  );
        		  jQuery("#map").animate(
        			  {width: '982px'},
        			  {queue: false, duration: 0,
        				  complete: function(){
        				  org.OpenGeoPortal.map.updateSize();}
        			  }
        		  );
        	  } else {
        		  panelSelector.show().animate(
            			  {width: '450px'},
            			  {queue: false, duration: 0,
            				  complete: function(){
            				  org.OpenGeoPortal.resultsTableObj.hideCol('ContentDate');
            				  org.OpenGeoPortal.resultsTableObj.sizeCells("searchResults");}  
            			  }
        		  );
        		  jQuery("#map").show().animate(
            			  {width: '549px'},
            			  {queue: false, duration: 0,
            				  complete: function(){
            				  org.OpenGeoPortal.map.updateSize();}
            			  }
        		  );
        	  }
        	  org.OpenGeoPortal.resultsTableObj.sizeCells("searchResults");
          	break;
          case rollRight:
        	  var panelSelector = jQuery("#left_col");
        	  if (typeof jQuery("#roll_right").attr('style') == 'undefined'){
        		  var testVal = false;
        	  } else if (jQuery("#roll_right").attr('style').indexOf('display: none') > -1){
        		  var testVal = false;
        	  } else {
        		  var testVal = true;
        	  }
        	  
        	  if ((panelSelector.width() < 450)||(testVal)){
        		  jQuery("#left_col").show().animate(
        			  {width: '450px'},
        			  {queue: false, duration: 0,
        				  complete: function(){
        				  org.OpenGeoPortal.resultsTableObj.sizeCells("searchResults");}  
        			  }
        		  );
        		  jQuery("#roll_right").animate(
        			  {width: 'hide'},
        			  {queue: false, duration: 0}
        		  );
        		  jQuery("#map").animate(
        			  {width: '549px'},
        			  {queue: false, duration: 0,
        				  complete: function(){
        				  org.OpenGeoPortal.map.updateSize();}
        			  }
        		  );
        	  } else {
        		  jQuery("#map").animate(
            			  {width: 'hide'},
            			  {queue: false, duration: 0,
            				  complete: function(){
            				  org.OpenGeoPortal.map.updateSize();}
            			  }
        		  );
        		  jQuery("#left_col").animate(
            			  {width: '1000px'},
            			  {queue: false, duration: 0,
            				  complete: function(){
            				  org.OpenGeoPortal.resultsTableObj.showCol('ContentDate');
            				  org.OpenGeoPortal.resultsTableObj.sizeCells("searchResults");
            			  	}
            			  }
        		  );        		  
        	  }
          	break;
          default:
          	alert('searchBoxResize fall-through.');
          }
    	});
};

org.OpenGeoPortal.UserInterface.prototype.mapFilterStatus = function(eventObj){
	if (arguments.length > 1){
		var selectVal = arguments[1];
	} else {
		var selectVal = jQuery(eventObj).attr("checked");
	}
	jQuery('.mapFilterFlag').each(function(){
		if (jQuery(this)[0].tagName == 'SPAN'){
			if (selectVal){
			jQuery(this).text("on");
			} else {
				jQuery(this).text("off");
			}
		} else {
			jQuery(this).attr("checked", selectVal);
		}
	});
	this.searchSubmit();
};

org.OpenGeoPortal.UserInterface.prototype.openOrganize = function(){
	var tableObj = org.OpenGeoPortal.Utility.whichTab().tableObject();
	if (typeof jQuery('#organizeDialog')[0] == 'undefined'){
		var fields = tableObj.tableHeadingsObj.getTableHeadings();
		var div = '<div id="organizeDialog" class="dialog">';
		div += '<table><thead>';
		div += '<tr><th>Column</th><th>Show</th><th>Sort By</th></tr>';
		div += '</thead><tbody>';			
		for (var i in fields){
			if (fields[i].organize){
				div += '<tr>';
				div += '<td>' + fields[i].columnConfig.sTitle + '</td>';
				div += '<td><input type="checkbox" class="columnVisibility" value="' + i + '" onclick="org.OpenGeoPortal.ui.toggleColumn(this)" /></td>';
				div += '<td><span class="columnSort" onclick="org.OpenGeoPortal.ui.chooseSort(\'' + i + '\')"><span class="columnValue">' + i + '</span></span></td>';			
				div += '</tr>';
			}
		}
		div += '</tbody></table></div>';
		jQuery('body').append(div);
		jQuery('#organizeDialog').dialog({
    		zIndex: 2999,
    		width: 200,
    		resizable: false,
    		autoOpen: false		
		});
	} else {
		
	}
	this.updateOrganizeDialog();
	jQuery('#organizeDialog').dialog('open');
};

org.OpenGeoPortal.UserInterface.prototype.chooseSort = function(columnName){
	org.OpenGeoPortal.Utility.whichTab().tableObject().sortColumns(columnName);
};

org.OpenGeoPortal.UserInterface.prototype.toggleColumn = function(thisObj){
	if (jQuery(thisObj).is(':checked')) {
		org.OpenGeoPortal.Utility.whichTab().tableObject().showCol(jQuery(thisObj).val());
	} else {
		org.OpenGeoPortal.Utility.whichTab().tableObject().hideCol(jQuery(thisObj).val());
	}
};

org.OpenGeoPortal.UserInterface.prototype.updateOrganizeDialog = function(){
	//these pieces should be also called when updated elsewhere
	var tableObj = org.OpenGeoPortal.Utility.whichTab().tableObject();
	var visibleColumns = tableObj.getVisibleColumns();
	jQuery("input:checkbox.columnVisibility").each(function(){
		jQuery(this).attr('checked', false);
		for (var visibleColumn in visibleColumns){
			if (jQuery(this).val() == visibleColumns[visibleColumn]){
				jQuery(this).attr('checked', true);
				continue;
			}
		}
	});
	var organize = tableObj.tableOrganize.getState();
	jQuery(".columnSort").each(function(){
		  jQuery(this).removeClass("columnSort_unsorted");
		  jQuery(this).removeClass("columnSort_sortedAsc");
		  jQuery(this).removeClass("columnSort_sortedDesc");
		  if (organize.organizeBy == jQuery(this).find("span").text()){
			  if (organize.organizeDirection == "asc"){
				  jQuery(this).addClass("columnSort_sortedAsc");  
			  } else if (organize.organizeDirection == "desc"){
				  jQuery(this).addClass("columnSort_sortedDesc");  
			  }
		  } else {
			  jQuery(this).addClass("columnSort_unsorted");  
		  }
	});
};

//should add to cartTable code
org.OpenGeoPortal.UserInterface.prototype.initSortable = function(){
	jQuery( "#savedLayers > tbody" ).sortable({helper: "original", opacity: .5, containment: "parent", 
		items: "tr", tolerance: "pointer", cursor: "move",
		start: function(event, ui){
				//this code is ugly...optimize
				jQuery("#savedLayers .resultsControls").each(function(){
					var rowObj = jQuery(this).parent()[0];
					console.log(rowObj);
					var tableObj = jQuery("#savedLayers").dataTable();
					tableObj.fnClose(rowObj);
					//why doesn't this close the row?
					tableObj.fnDraw(false);
				});
			},
		stop: function(event, ui){
		 		var dataArr = [];
		 		var tableObj = jQuery("#savedLayers").dataTable();
		 		dataArr = tableObj.fnGetData();
		 		var newArr = [];
		 		var openCount = 0;
				jQuery("#savedLayers > tbody > tr").each(function(index, Element){
					var dataTableIndex = tableObj.fnGetPosition(Element);
					if (typeof dataTableIndex == 'number'){
						newArr[index - openCount] = dataArr[dataTableIndex];
					} else {
						openCount += 1;
					}
				});
				tableObj.fnClearTable(false);
				tableObj.fnAddData(newArr);
				var tableLength = newArr.length;
				for (var i in newArr){
					if (typeof org.OpenGeoPortal.map.getLayersByName(newArr[i][0])[0] !== 'undefined'){
					var layer = org.OpenGeoPortal.map.getLayersByName(newArr[i][0])[0];
					org.OpenGeoPortal.map.setLayerIndex(layer, tableLength - (i+1));
					}
				}
				
				/*jQuery("#savedLayers .resultsControls").each(function(){
					jQuery(this).parent().show();
				});*/
				//tableObj.fnDraw();
				//jQuery( "#savedLayers > tbody" ).sortable("refresh");
				org.OpenGeoPortal.cartTableObj.callbackExpand();
			
			}
	});
};


org.OpenGeoPortal.UserInterface.prototype.openControl = function(thisObj){
	var control = jQuery(thisObj).find("div.controlContainer");
	if (control.css("display") == "none"){
		var offsetRight = control.prev().position().left - (control.width() - control.prev().width()) - 12;
		control.css("left", offsetRight);
		control.css("display", "block");
	}
};

org.OpenGeoPortal.UserInterface.prototype.closeControl = function(thisObj){
	var control = jQuery(thisObj).find("div.controlContainer");
	control.css("display", "none");
};

org.OpenGeoPortal.UserInterface.prototype.toggleChecksSaved = function(eventObj, targetElement){
	if (org.OpenGeoPortal.cartTableObj.numberOfResults() > 0){
		this.toggleChecksAll(eventObj, targetElement);
	}
};

org.OpenGeoPortal.UserInterface.prototype.updateSavedLayersNumber = function(){
	jQuery('#savedLayersNumber').text('(' + org.OpenGeoPortal.cartTableObj.numberOfResults() + ')');
};

org.OpenGeoPortal.UserInterface.prototype.toggleChecksAll = function(eventObj, targetElement){
	if (jQuery(eventObj).attr('alt') == "Select All"){
		jQuery(eventObj).attr('alt', "Unselect All");
		jQuery(eventObj).attr('src', "media/button_clear.png");	
		jQuery('#' + targetElement + " :checkbox").each(function(){
			jQuery(this).attr('checked', true);
		});
	} else {
		jQuery(eventObj).attr('alt', "Select All");
		jQuery(eventObj).attr('src', "media/button_selectall.png");				
		jQuery('#' + targetElement + " :checkbox").each(function(){
			jQuery(this).attr('checked', false);
		});
	}
};

org.OpenGeoPortal.UserInterface.prototype.downloadDialog = function(){
	var that = this;
	//first, check to see if anything is in savedLayers & checked
	var checkedRows = jQuery("#savedLayers .colChkBoxes :checked");
    if (checkedRows.length == 0){
    	var dialogContent = 'No layers have been selected.';
    	//this should probably call a dialog instance for error messages/notifications
    } else {
    	//generate a list of appropriate choices for the chosen layers
    	//for now a best guess
    	var dialogContent = "<label for=\"downloadType\">File format:</label><select id=\"downloadType\"> \n";
    	dialogContent += "<option value=\"shp\">shapefile</option> \n";
    	dialogContent += "<option value=\"kml\">KML</option> \n";
    	//dialogContent += "<option value=\"kmz\">KMZ</option> \n";
    	dialogContent += "</select><br/> \n";
    	dialogContent += "<label for=\"checkClip\">Clip data to map extent</label><input id=\"checkClip\" type=\"checkbox\" checked=\"checked\" />";
    }
    
    if (typeof jQuery('#downloadDialog')[0] == 'undefined'){
    	var downloadDiv = '<div id="downloadDialog" class="dialog"> \n';
        downloadDiv += dialogContent;
        downloadDiv += '</div> \n';
    	jQuery('body').append(downloadDiv);
    	jQuery("#downloadDialog").dialog({
    		zIndex: 3000,
    		autoOpen: false,
    		minHeight: '30px',
    		title: "DOWNLOAD",
    		resizable: false,
			buttons: {
				Cancel: function() {
					jQuery(this).dialog('close');
				},
				Download: function() {
					//this function should get the checked layers from savedLayers,
					//get the user's choice for download option & complete the operation,
					//which for now is submitting a properly formatted URL
		    		switch (jQuery('#downloadType').val()){
		    		case 'shp':
		    			var format = "shapefile";
		    			that.requestDownload(format);
		    			return;
		    			break;
		    		case 'kml':
		    			var format = "application/vnd.google-earth.kml+xml";
		    			break;
		    		case 'kmz':
		    			//construct a url to send to geoserver
		    			var format = "application/vnd.google-earth.kmz";
		    			break;
		    		default: throw new Error("This download format is unavailable.");
		    		}
		    		var serverURL = {};
		    		var minBbox = org.OpenGeoPortal.map.maxExtent.toBBOX();
			    	//construct appropriate url
	    		    var tableObj = jQuery("#savedLayers").dataTable();
		    		checkedRows.each(function(){
		    			var rowNode = jQuery(this).parentsUntil('tr').last().parent();
		    			//console.log(rowNode[0]);
		    			var aPos = tableObj.fnGetPosition(rowNode[0]);
		   				//console.log(jQuery(this));
		   				var aData = tableObj.fnGetData(aPos);
		   				if (format == 'shapefile'){
		    				var currentURL = org.OpenGeoPortal.InstitutionInfo[aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Institution')]].servers.download[0];
		   				} else {
		    				var currentURL = org.OpenGeoPortal.InstitutionInfo[aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Institution')]].servers.WMS[0];
		    			}
		    			if (typeof serverURL[currentURL] == 'undefined'){
		    				serverURL[currentURL] = new Array();
		   				}
		    			var currentName = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('WorkspaceName')] + ':' + aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Name')];
		   				serverURL[currentURL].push({"Name": aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Name')], 
		   					"DataType": aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('DataType')]});
		   			});   		
		    		var bbox;
		    		if (jQuery('#checkClip').attr('checked') == true){
		    			bbox = org.OpenGeoPortal.map.getExtent();
		    			var lowerLeft = org.OpenGeoPortal.map.MercatorToWGS84(bbox.left, bbox.bottom);
		    			var upperRight = org.OpenGeoPortal.map.MercatorToWGS84(bbox.right, bbox.top);
		    			bbox = lowerLeft.lon + ',' + lowerLeft.lat + ',' + upperRight.lon + ',' + upperRight.lat;
		    		} else {
		    			bbox = minBbox;
		    		}
		    		for(var server in serverURL){
		    			//need width, height, bbox
		    			/*if ((server != savedLayersTableObj.institutionToServer['MIT'].servers.WMS[0])&&
		    					(server != savedLayersTableObj.institutionToServer['MIT'].servers.download[0])){
		    				//throw new Error("Downloads from this server are not currently available");
		    				continue;
		    			}*/
		    			var allLayers = serverURL[server];
		    			if (format == 'shapefile'){
		    				for (var layerInfo in allLayers){
		    					if (server.indexOf('wfs') > 0){
		    						var url = server + "?service=wfs&version=1.1.0&request=GetFeature&outputFormat=shape-zip&srsName=EPSG:4326";
		    				    	url += /*"&bbox=" + bbox + */"&typeName=" + allLayers[layerInfo].Name;
		    				    	//cql_filter=INTERSECT(the_geom,%20POLYGON%20(-74.817265%2040.5296504))
		    					} else {
		    						var url = server + '?bbox=' + bbox + '&geom=' + allLayers[layerInfo].DataType + '&layer=' + allLayers[layerInfo].Name;
		    					}
	    						jQuery("body").append('<iframe style="display:none" src="' + url + '"></iframe>');
		    				}
		    			} else {
		    				var requestedLayers = [];
		    				for (var layerInfo in allLayers){
		    					requestedLayers.push(allLayers[layerInfo].Name);
		    				}
		    				var requestObj = {};
		    				requestObj.type = 'download';
		    				requestObj.server = server;
		    				requestObj.format = format;
		    				requestObj.bbox = bbox;
		    				requestObj.srs = 'EPSG:4326';
		    				requestObj.width = '800';
		    				requestObj.height = '600';
		    				requestObj.layers = requestedLayers.join();
		    				org.OpenGeoPortal.ui.downloadFromMapServer(requestObj);
		    			}
		    		}
				}
			}
		});    	  
    	jQuery("#downloadDialog").dialog('open');
    } else {
    	//replace dialog text/controls & open the instance of 'dialog' that already exists
		  jQuery("#downloadDialog").html(dialogContent);
		  jQuery("#downloadDialog").dialog('open');
	}
};

org.OpenGeoPortal.UserInterface.prototype.isClipped = function(){
	return jQuery('#checkClip').attr('checked');
};

org.OpenGeoPortal.UserInterface.prototype.requestDownload = function(fileFormat){
	var bbox;
	var arrBbox = new Array();
	var clipped = this.isClipped();
	if (clipped){
		//if this is true, we should also make sure that part or all of the requested layer is in the extent
		//if not, it should be excluded
		bbox = org.OpenGeoPortal.map.getExtent();
		var lowerLeft = org.OpenGeoPortal.map.MercatorToWGS84(bbox.left, bbox.bottom);
		var upperRight = org.OpenGeoPortal.map.MercatorToWGS84(bbox.right, bbox.top);
	} else {
		bbox = org.OpenGeoPortal.map.maxExtent.toBBOX();
		arrBbox = bbox.split(",");
		var lowerLeft = org.OpenGeoPortal.map.MercatorToWGS84(arrBbox[0], arrBbox[1]);
		var upperRight = org.OpenGeoPortal.map.MercatorToWGS84(arrBbox[2], arrBbox[3]);
	}
	arrBbox[0] = lowerLeft.lon;
	arrBbox[1] = lowerLeft.lat;
	arrBbox[2] = upperRight.lon;
	arrBbox[3] = upperRight.lat;
	var layerObj = this.getLayerList({clipped: arrBbox});
	var layerIds = [];
	for (var layer in layerObj){
		layerIds.push(layer);
	}
	var requestObj = {};
	requestObj.bbox = arrBbox;
	requestObj.format = fileFormat;
	requestObj.layers = layerIds;
	requestObj.height = 680;//does this parameter actually matter for this type of request?
	requestObj.width = 540;
	var params = {
			url: "downloader.jsp",
			data: requestObj,
			dataType: "text",
			type: "POST",
			traditional: true,
			success: function(data){
				//close the download box;
				jQuery("#downloadDialog").dialog("close");
				jQuery("body").append('<iframe style="display:none" src="' + data + '"></iframe>');
			}
	};
	jQuery.ajax(params);
};

org.OpenGeoPortal.UserInterface.prototype.getLayerList = function(params){
	if (arguments.length == 0){
		params = {};
		params.clipped = false;
	}
	layerInfo = {};
	var tableObj = jQuery("#savedLayers").dataTable();
	var checkedRows = jQuery("#savedLayers .colChkBoxes :checked");
	checkedRows.each(function(){
		var rowNode = jQuery(this).parentsUntil('tr').last().parent();
		var aPos = tableObj.fnGetPosition(rowNode[0]);
		var aData = tableObj.fnGetData(aPos);
		var minX = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('MinX')];
		var minY = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('MinY')];
		var maxX = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('MaxX')];
		var maxY = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('MinY')];
		var isValidLayer = true;
		if (params.clipped != false){
			//do a test to see if the layer's bbox is within the clip extent
			var layerBounds = new OpenLayers.Bounds();
			layerBounds.extend(new OpenLayers.LonLat(minX,minY));
			layerBounds.extend(new OpenLayers.LonLat(maxX,maxY));

			var clipBounds = new OpenLayers.Bounds();
			clipBounds.extend(new OpenLayers.LonLat(params.clipped[0],params.clipped[1]));
			clipBounds.extend(new OpenLayers.LonLat(params.clipped[2],params.clipped[3]));
			//this isn't working yet
			//isValidLayer = layerBounds.intersectsBounds(clipBounds);
		}
		if (isValidLayer){
			var layerID = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('LayerId')];
			layerInfo[layerID] = {};
			layerInfo[layerID].name = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Name')];
			layerInfo[layerID].institution = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Institution')];
			layerInfo[layerID].dataType = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('DataType')];
			layerInfo[layerID].access = aData[org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('Access')];
			layerInfo[layerID].bounds = [minX, minY, maxX, maxY];
		}
	});
	return layerInfo;
};

org.OpenGeoPortal.UserInterface.prototype.downloadFromMapServer = function(requestObj) {
	//modularize wms call so I can use the same code for 'save image'
	/*if (!jQuery("#attachment")[0]){
		jQuery("body").append('<div id="attachment" style="display:none;"></div>');
	}*/
	var url = "WMSGetMapProxy.jsp?server=" + requestObj.server + '&format=' + requestObj.format + '&bbox=' + requestObj.bbox;
	url += '&srs=' + requestObj.srs + '&layers=' + requestObj.layers;
	url += '&width=' + requestObj.width + '&height=' + requestObj.height + '&type=' + requestObj.type;
	if (typeof requestObj.sld != 'undefined'){
		url += '&sld=' + requestObj.sld;
	}
	jQuery("#downloadDialog").dialog("close");
	jQuery("body").append('<iframe style="display:none" src="' + url + '"></iframe>');
};

//not done yet
org.OpenGeoPortal.UserInterface.prototype.saveImage = function(){
	//check to see if layer is visible and in the extent
	var imageFormat = 'png';
	switch (imageFormat){
	case 'jpeg':
		var format = "image/jpeg";
		break;
	case 'png':
		var format = "image/png";
		break;
	case 'bmp':
		var format = "image/bmp";
		break;
	default: throw new Error("This image format (" + imageFormat + ") is unavailable.");
	}
	var serverURL = {};
	var minBbox;
	//construct appropriate url
	var numberOfLayers = 0;
    for (var layer in org.OpenGeoPortal.map.layers){
    	var currentLayer = org.OpenGeoPortal.map.layers[layer];
    	if (currentLayer.CLASS_NAME != "OpenLayers.Layer.WMS"){
    		continue;
    	}
    	if (currentLayer.visibility == false){
    		continue;
    	}
		//do a test to see if the layer's bbox is within the clip extent
		/*var layerBounds = currentLayer.getDataExtent();
    	console.log(currentLayer.getDataExtent());

		if (typeof layerBounds == 'undefined'){
			continue;
		}
	    
		var mapBounds = org.OpenGeoPortal.map.returnExtent();
		var isValidLayer = layerBounds.intersectsBounds(mapBounds);
		*/
    	var currentURL = currentLayer.url;
    	//transform cache url to wms url
    	currentURL = org.OpenGeoPortal.InstitutionInfo.tilecacheToWMS(currentURL);
		if (typeof serverURL[currentURL] == 'undefined'){
			serverURL[currentURL] = new Array();
		}
		var sld = org.OpenGeoPortal.layerState.getState(currentLayer.name, "sld");
		var opacity = org.OpenGeoPortal.layerState.getState(currentLayer.name, "opacity");
		//insert this opacity value into the sld to pass to the wms server
		var storedName = org.OpenGeoPortal.layerState.getState(currentLayer.name, "wmsName");
		layerObj = {};
		if (storedName == ''){
			layerObj.Name = currentLayer.params.LAYERS;
		} else {
			layerObj.Name = storedName;
		}
		layerObj.opacity = opacity;
		if (typeof sld !== 'undefined'){
			if (typeof sld.symbolizer !== 'undefined'){
				layerObj.sld = sld;
			}
		}
		serverURL[currentURL].push(layerObj);
		numberOfLayers++;
    }
    if (numberOfLayers == 0){
    	throw new Error("There are no layers in the current extent.");
    }
	var bbox;
	bbox = org.OpenGeoPortal.map.getExtent().toBBOX();
	for(var server in serverURL){
		//this will only work for images from a single server...we need a server side script that will overlay layers in the correct order
		//need width, height, bbox
		var allLayers = serverURL[server];
		var requestedLayers = [];
		var mergedSLD = [];
		for (var layerInfo in allLayers){
			requestedLayers.push(allLayers[layerInfo].Name);
			if (typeof allLayers[layerInfo].sld !== 'undefined'){
				mergedSLD.push({wmsName: allLayers[layerInfo].Name, layerStyle: allLayers[layerInfo].sld});
			}
		}			
		var requestObj = {};
		requestObj.type = 'image';
		requestObj.server = server;
		requestObj.format = format;
		requestObj.bbox = bbox;
		requestObj.srs = 'EPSG:900913';
		requestObj.width = jQuery('#map').width();
		requestObj.height = jQuery('#map').height();
		if (mergedSLD.length > 0){
			console.log(org.OpenGeoPortal.map.createSLDFromParams(mergedSLD));
			requestObj.sld = escape(org.OpenGeoPortal.map.createSLDFromParams(mergedSLD));
		}
		requestObj.layers = requestedLayers.join();
		this.downloadFromMapServer(requestObj);
	}   	  
};

org.OpenGeoPortal.UserInterface.prototype.saveKML = function() {
	var bbox;
	var arrBbox = new Array();
	var clipped = this.isClipped();
	var serverURL = {};
	if (clipped){
		//if this is true, we should also make sure that part or all of the requested layer is in the extent
		//if not, it should be excluded
		bbox = org.OpenGeoPortal.map.getExtent();
		var lowerLeft = org.OpenGeoPortal.map.MercatorToWGS84(bbox.left, bbox.bottom);
		var upperRight = org.OpenGeoPortal.map.MercatorToWGS84(bbox.right, bbox.top);
	} else {
		bbox = org.OpenGeoPortal.map.maxExtent.toBBOX();
		arrBbox = bbox.split(",");
		var lowerLeft = org.OpenGeoPortal.map.MercatorToWGS84(arrBbox[0], arrBbox[1]);
		var upperRight = org.OpenGeoPortal.map.MercatorToWGS84(arrBbox[2], arrBbox[3]);
	}
	arrBbox[0] = lowerLeft.lon;
	arrBbox[1] = lowerLeft.lat;
	arrBbox[2] = upperRight.lon;
	arrBbox[3] = upperRight.lat;
	var layerObj = this.getLayerList({clipped: arrBbox});
	for (var layer in layerObj){
		var currentInstitution = layerObj[layer].institution;
    	var currentURL = org.OpenGeoPortal.InstitutionInfo[currentInstitution].servers.WMS[0];
		if (typeof serverURL[currentURL] == 'undefined'){
			serverURL[currentURL] = new Array();
		}
		serverURL[currentURL].push(layerObj[layer]);
	}
	
	for(var server in serverURL){
		//this will only work for images from a single server...we need a server side script that will overlay layers in the correct order
		//need width, height, bbox
		var allLayers = serverURL[server];
		var requestedLayers = [];
		for (var layerInfo in allLayers){
			requestedLayers.push(allLayers[layerInfo].Name);
		}			
		var requestObj = {};
		requestObj.server = server;
		requestObj.format = "kml";
		requestObj.bbox = bbox;
		requestObj.srs = 'EPSG:900913';
		requestObj.width = jQuery('#map').width();
		requestObj.height = jQuery('#map').height();
		requestObj.layers = requestedLayers.join();
		this.downloadFromMapServer(requestObj);
	}  
};

//based on Dave's code
org.OpenGeoPortal.UserInterface.prototype.getParamsFromUrl = function() {
	var params = {};
    var layers = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if ((hash[0] == "layer%5B%5D")||(hash[0] == "layer[]")){
        	layers.push(hash[1]);
        } else {
        	params[hash[0]] = hash[1];
        }
    }
    if (layers.length > 0){
    	params.layer = layers;
    }
    return params;
};

org.OpenGeoPortal.UserInterface.prototype.addSharedLayersToCart = function(){
	var params = this.getParamsFromUrl();

	if (typeof params.layer == 'undefined'){
		return;
	}
    var solr = new org.OpenGeoPortal.Solr();
	var query = solr.getInfoFromLayerIdQuery(params.layer);
	solr.sendToSolr(query, this.getLayerInfoJsonpSuccess, this.getLayerInfoJsonpError, this);
	var sharedExtent = params.minX + ',' + params.minY + ',' + params.maxX + ',' + params.maxY;
	org.OpenGeoPortal.map.zoomToLayerExtent(sharedExtent);
	jQuery("#tabs").tabs({selected: 2});
	this.initSortable();
};

org.OpenGeoPortal.UserInterface.prototype.getLayerInfoJsonpSuccess = function(data, newContext){
	newCartData = org.OpenGeoPortal.cartTableObj.processData(data);
	for(var i in newCartData){
		newContext.addLayerToCart(newCartData[i]);
	}
};

org.OpenGeoPortal.UserInterface.prototype.getLayerInfoJsonpError = function(){
	  throw new Error("The attempt to retrieve layer information from layerIDs failed.");
};
//solr query against layerIds
//process data functions, pass to this function
org.OpenGeoPortal.UserInterface.prototype.addLayerToCart = function(layerData){
	var savedTable = jQuery('#savedLayers').dataTable();
	var currentData = savedTable.fnGetData();
	layerData = [layerData];
	var newData = layerData.concat(currentData);
	savedTable.fnClearTable();
	savedTable.fnAddData(newData);
	jQuery('#savedLayersNumber').text('(' + org.OpenGeoPortal.cartTableObj.numberOfResults() + ')');
	//console.log(layerData);
	var layerID = layerData[0][org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('LayerId')];
	var dataType = layerData[0][org.OpenGeoPortal.cartTableObj.tableHeadingsObj.getColumnIndex('DataType')];
    if (!org.OpenGeoPortal.layerState.layerStateDefined(layerID)){
    	org.OpenGeoPortal.layerState.addNewLayer(layerID, {"dataType": dataType, "inCart": true});
    } else {
    	org.OpenGeoPortal.layerState.setState(layerID, {"inCart": true});
    }
};

org.OpenGeoPortal.UserInterface.prototype.shareLayers = function(){
	var layers = [];
	var layerObj = this.getLayerList();
	for (var layer in layerObj){
		layers.push(layer);
	}
    if (layers.length == 0){
    	var dialogContent = 'No layers have been selected.';
    	//this should probably call a dialog instance for error messages/notifications
    } else {
    	//console.log(top.location);
    	if (top.location.href.indexOf("openGeoPortalHome.jsp") < 0){
    		var shareLink = "http://" + top.location.host + "/openGeoPortalHome.jsp";
    	} else {
    		var shareLink = "http://" + top.location.host + top.location.pathname;
    	}
    	var geodeticBbox = org.OpenGeoPortal.map.getGeodeticExtent();
    	var queryString = '?' + jQuery.param({ layer: layers, minX: geodeticBbox.left, minY: geodeticBbox.bottom, maxX: geodeticBbox.right, maxY: geodeticBbox.top });
    	shareLink += queryString;
    	var dialogContent = '<textarea id="shareText" >' + shareLink + '</textarea> \n';
    	dialogContent += '<p>Copy and paste the link above to share your layers.</p>';
    }
    
    if (typeof jQuery('#shareDialog')[0] == 'undefined'){
    	var shareDiv = '<div id="shareDialog" class="dialog"> \n';
        shareDiv += dialogContent;
        shareDiv += '</div> \n';
    	jQuery('body').append(shareDiv);
    	jQuery("#shareDialog").dialog({
    		zIndex: 3000,
    		autoOpen: false,
    		height: 150,
    		width: 495,
    		title: 'SHARE LAYERS LINK',
    		resizable: false,
			buttons: {
				Close: function() {
					jQuery(this).dialog('close');
				}
    	}});
        } else {
        	//replace dialog text/controls & open the instance of 'dialog' that already exists
    		  jQuery("#shareDialog").html(dialogContent);
    	}
	jQuery("#shareDialog").dialog('open');
    jQuery('#shareText').focus(function(){
        // Select input field contents
        this.select();
    });
    jQuery('#shareText').focus();
};

org.OpenGeoPortal.UserInterface.prototype.shareServices = function(){
	var layerObj = this.getLayerList();
	var layers = [];
	//console.log(layerObj);
	for (var layer in layerObj){
		layers.push(layer);
	}

    if (layers.length == 0){
    	var dialogContent = 'No layers have been selected.';
    	//this should probably call a dialog instance for error messages/notifications
    } else {
    	var dialogContent = '';
    	for (var layer in layerObj){
    		if (layerObj[layer].access != 'Public'){
    			continue;
    			//check for login info in cookie, if not there, prompt for login
    		} else {
    			var serverLocation = org.OpenGeoPortal.InstitutionInfo[layerObj[layer].institution].servers.WMS[0];
    			var format = "image/png";//is this right?
    			var bbox = layerObj[layer].bounds.join();
    			var layerName = layerObj[layer].name;
    			var srs = "EPSG:4236";
    			var shareLink = serverLocation.substr(0, serverLocation.indexOf('/wms')) + "/sde/layerName/wms";//?service=wms&version=1.1.1&request=GetMap&format=" + format + "&SRS=" + srs;
    			//shareLink += "&styles=&bbox=" + bbox + "&layers=" + layerName;
    			dialogContent += '<textarea class="shareServicesText" >' + shareLink + '</textarea> <br />\n';
    		}
    	}
    	dialogContent += '<p>Copy and paste the links above to your wms services.</p>';
    }
    
    if (typeof jQuery('#shareDialog')[0] == 'undefined'){
    	var shareDiv = '<div id="shareServicesDialog" class="dialog"> \n';
        shareDiv += dialogContent;
        shareDiv += '</div> \n';
    	jQuery('body').append(shareDiv);
    	jQuery("#shareServicesDialog").dialog({
    		zIndex: 3000,
    		autoOpen: false,
       		height: 'auto',
    		width: 495,
			buttons: {
				Close: function() {
					jQuery(this).dialog('close');
				}
    	}});
        } else {
        	//replace dialog text/controls & open the instance of 'dialog' that already exists
    		  jQuery("#shareServicesDialog").html(dialogContent);
    	}
	jQuery("#shareServicesDialog").dialog('open');
    jQuery('.shareServicesText').first().focus(function(){
        // Select input field contents
        this.select();
    });
    jQuery('.shareServicesText').first().focus();
};


org.OpenGeoPortal.UserInterface.prototype.loginDialog = function(){
	var dialogContent = '<p>login functionality is not currently available</p> \n';
	//dialogContent += '<p>Copy and paste the link above to share your layers.</p>';

if (typeof jQuery('#loginDialog')[0] == 'undefined'){
	var shareDiv = '<div id="loginDialog" class="dialog"> \n';
    shareDiv += dialogContent;
    shareDiv += '</div> \n';
	jQuery('body').append(shareDiv);
	jQuery("#loginDialog").dialog({
		zIndex: 3000,
		autoOpen: false,
		width: 'auto',
		resizable: false,
		buttons: {
			Close: function() {
				jQuery(this).dialog('close');
			}
	}});
    } else {
    	//replace dialog text/controls & open the instance of 'dialog' that already exists
		  jQuery("#loginDialog").html(dialogContent);
	}
jQuery("#loginDialog").dialog('open');

};

//toggle the attribute info button & functionality
org.OpenGeoPortal.UserInterface.prototype.toggleFeatureInfo = function(thisObj, layerID, displayName){
	  if (!org.OpenGeoPortal.layerState.getState(layerID, "getFeature")){
		  //update layer state
		  org.OpenGeoPortal.layerState.setState(layerID, {"getFeature": true});
		  org.OpenGeoPortal.layerState.getFeatureTitle = displayName;
	  } else {
		  //update layer state, turn off get feature 
		  org.OpenGeoPortal.layerState.setState(layerID, {"getFeature": false});
	  }

};

//get the color from the layer state object to use for the shown swatch
org.OpenGeoPortal.UserInterface.prototype.setPaletteColor = function(layerID){
	  var paletteColor = org.OpenGeoPortal.layerState.getState(layerID, "color");
	  var escapedLayerID = org.OpenGeoPortal.Utility.idEscape(layerID);
	  jQuery(".colorPalette").each(function(){
		  //console.log(["iterate", paletteColor]);
		  if (jQuery(this).is('[id$=' + escapedLayerID + ']')){
			  //console.log("match");
			  jQuery(this).css("background-color", paletteColor);
		  }
	  });
};

//create the color picker dialog box
org.OpenGeoPortal.UserInterface.prototype.colorDialog = function(layerID, dataType){
	  //create a hidden div w/ the dialog info
	  //create a new dialog instance, or just open the dialog if it already exists
	  //if it already exists, function should reset color picker to match layer
	  //button to apply color, button to cancel
	  //apply color changes state object for the layer
	  //call map function to apply style from the state object
	var allColors = {};
	allColors.grey = ["#828282", "#9c9c9c", "#b2b2b2", "#cccccc", "#e1e1e1", "#ffffff"];
	allColors.red = ["#730000", "#a80000", "#e80000", "#ff0000", "#ff7f7f", "#ffbebe"];
	allColors.darkOrange = ["#732600", "#a83800", "#e64c00", "#ff5500", "#ffa77f", "#ffebbe"];
	allColors.orange = ["#734c00", "#a87000", "#e69800", "#ffaa00", "#ffd37f", "#ffebaf"];
	allColors.yellow = ["#737300", "#a8a800", "#e6e600", "#ffff00", "#ffff73", "#ffffbe"];
	allColors.grassGreen = ["#426e00", "#426e00", "#98e600", "#aaff00", "#d1ff73", "#e9ffbe"];
	allColors.green = ["#267300", "#38a800", "#4ce600", "#55ff00", "#a3ff73", "#d3ffbe"];
	allColors.cyan = ["#00734c", "#00a884", "#00e6a9", "#00ffc5", "#73ffdf", "#beffe8"];
	allColors.blue = ["#004c73", "#0084a8", "#00a9e6", "#00c5ff", "#73dfff", "#bee8ff"];
	allColors.indigo = ["#002673", "#0049a9", "#005ce6", "#0070ff", "#73b2ff", "#bed2ff"];
	allColors.violet = ["#4c0073", "#8400a8", "#a900e6", "#c500ff", "#df73ff", "#e8beff"];
	allColors.pink = ["#780f52", "#a80084", "#e00fa7", "#ff00c5", "#ff73df", "#ffbee8"];
	var currentColorSelection = org.OpenGeoPortal.layerState.getState(layerID, "color");
	  if (typeof jQuery('#colorDialog')[0] == 'undefined'){
		  var dialogDiv = '<div id="colorDialog" class="dialog"> \n';
		  dialogDiv += '</div> \n';
		  jQuery('body').append(dialogDiv);
	  }

	  var colorDiv = '<table><tbody>';
	  for (var row in allColors){
		  colorDiv += '<tr>';
		  for (var cell in allColors[row]){
			  colorDiv += '<td class="colorCellParent">';
			  var currentColorValue = allColors[row][cell];
			  if (currentColorValue == currentColorSelection){
				  var selectionClass = " colorCellSelected";
			  } else {
				  var selectionClass = "";
			  }
			  colorDiv += '<div class="colorCell' + selectionClass + '" onclick="org.OpenGeoPortal.ui.selectColorCell(this, \'';
			  colorDiv += layerID + '\', \'' + dataType + '\');" style="background-color:' + allColors[row][cell] + '"></div>';
			  colorDiv += '</td>';
		  }
		  colorDiv += '</tr>';
	  	}
	  colorDiv += '</tbody></table>';
	  jQuery('#colorDialog').html(colorDiv);
	  jQuery("#colorDialog").dialog({
		zIndex: 2999,
		autoOpen: false,
		width: 'auto',
		height: 'auto',
		title: '<img src="media/header_colors.png" />',
		resizable: false
	  });    	  
	  jQuery("#colorDialog").dialog('open');
};

org.OpenGeoPortal.UserInterface.prototype.selectColorCell = function(thisObj, layerID, dataType){
	jQuery('.colorCell').removeClass('colorCellSelected');
	jQuery(thisObj).addClass('colorCellSelected');
	//for IE
	var selectedColor = jQuery('div.colorCellSelected').css("background-color");
	if (selectedColor.indexOf("rgb") > -1){
		selectedColor = org.OpenGeoPortal.Utility.rgb2hex(selectedColor);
	}
	org.OpenGeoPortal.layerState.setState(layerID, {color: selectedColor});
	this.setPaletteColor(layerID);
	org.OpenGeoPortal.map.changeStyle(layerID, dataType);
};

//toggle whether the applied style has an outline
org.OpenGeoPortal.UserInterface.prototype.toggleOutline = function(thisObj, layerID, dataType){
	 //sets state object to match checkbox value, calls map function to apply the style to the layer
	 if (jQuery(thisObj).is(':checked') == true){
		 org.OpenGeoPortal.layerState.setState(layerID, {"graphicWidth": 1});
	 } else {
		 org.OpenGeoPortal.layerState.setState(layerID, {"graphicWidth": 0}); 
	 }
	 org.OpenGeoPortal.map.changeStyle(layerID, dataType);  
};

org.OpenGeoPortal.UserInterface.prototype.mouseCursor = function(){
	jQuery('.olMap').css('cursor', "-moz-grab");
	jQuery('div.olControlZoomBoxItemInactive').bind('click', function(){
		jQuery('.olMap').css('cursor', "-moz-zoom-in");
		var mapLayers = org.OpenGeoPortal.map.layers;
		for (var i in mapLayers){
			var currentLayer = mapLayers[i];
			if (org.OpenGeoPortal.layerState.layerStateDefined(currentLayer.name)){
				if (org.OpenGeoPortal.layerState.getState(currentLayer.name, "getFeature")){
					currentLayer.events.unregister("click", currentLayer, org.OpenGeoPortal.map.wmsGetFeature);
				}
			} else {
				continue;
			}
		}
		org.OpenGeoPortal.layerState.resetState('getFeature');
		jQuery('.attributeInfoControl').attr('src', 'media/icon_crosshair_off.png');
	});
	jQuery('.olControlNavigationItemActive').bind('click', function(){
		jQuery('.olMap').css('cursor', "-moz-grab");
		var mapLayers = org.OpenGeoPortal.map.layers;
		for (var i in mapLayers){
			var currentLayer = mapLayers[i];
			if (org.OpenGeoPortal.layerState.layerStateDefined(currentLayer.name)){
				if (org.OpenGeoPortal.layerState.getState(currentLayer.name, "getFeature")){
					currentLayer.events.unregister("click", currentLayer, org.OpenGeoPortal.map.wmsGetFeature);
				}
			} else {
				continue;
			}
		}
		org.OpenGeoPortal.layerState.resetState('getFeature');
		jQuery('.attributeInfoControl').attr('src', 'media/icon_crosshair_off.png');
	});
};

org.OpenGeoPortal.UserInterface.prototype.resizePanels = function(){
	jQuery("#map").resizable({handles: 'w', ghost: true,
		minWidth: jQuery(".olControlPanel").width() + jQuery("#geosearchDiv").width() + jQuery("#mapLoadIndicator").width(),
		maxWidth: jQuery("#container").width() - jQuery("#basicSearchBox").width(),
		stop: function(event, ui) {
			var widthDelta = ui.size.width - ui.originalSize.width;
			var newWidth = jQuery("#container").width() - jQuery("#map").width();
			jQuery("#map").css("left", 0);
			jQuery("#left_col").width(newWidth -1);

			org.OpenGeoPortal.Utility.whichTab().tableObject().getTableObj().fnDraw();
			org.OpenGeoPortal.map.updateSize();
		}
	});
};

org.OpenGeoPortal.UserInterface.prototype.loadIndicatorId = 0;

org.OpenGeoPortal.UserInterface.prototype.loadIndicator = function(div, status){
	var indicator = jQuery('#' + div);
	if (status == 'show'){
		indicator.css("background-image", "url('media/progress.png')");
		indicator.fadeIn();
		//clearInterval first.  Otherwise, the interval queue will keep going if the indicator is still showing
		clearInterval(this.loadIndicatorId);
		this.loadIndicatorId = setInterval('jQuery("#' + div + '").css("background-position", function(a,b){var y = parseFloat(b.substr(b.indexOf(" "))); y -= 25; return "0px " + y + "px";})', 84);
		
	}else if (status == 'hide'){
		//var that = this;
		indicator.fadeOut();
		clearInterval(this.loadIndicatorId);
	}
};
